package com.killer_jin.core.common.util.poi;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * excel相关工具类
 *
 * @author jingchen
 * @since 2019/4/18
 */
public class WorkbookUtils {

    public static String getCellValue(Cell cell) {
        String cellValue = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        double cellDouble = Double.parseDouble(cell.getStringCellValue());
                        Date cellDate = HSSFDateUtil.getJavaDate(cellDouble);
                        cellValue = sdf.format(cellDate);
                    } else {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cellValue = cell.getStringCellValue();
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    cellValue = String.valueOf(cell.getCellFormula());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    cellValue = "";
                    break;
                case Cell.CELL_TYPE_ERROR:
                    cellValue = "";
                    break;
                default:
                    cellValue = cell.toString().trim();
                    break;
            }
        }
        return cellValue.trim();
    }

    public static String getCellValue(final Row row, final int i) {
        Cell cell = row.getCell(i);
        return WorkbookUtils.getCellValue(cell);
    }

    public static Cell setCellValue(final Row row, final Integer colIndex, final String value) {
        Cell cell = row.createCell(colIndex);
        cell.setCellValue(value);
        return cell;
    }

    public static void setRowValues(final Row headRow, final String... values) {
        for (int i = 0; i < values.length; i++) {
            setCellValue(headRow, i, values[i]);
        }
    }

    public static void createHeadRow(final Sheet sheet, final String... titles) {
        Row headRow = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = headRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
    }
}
